package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"im/app/conf"
	"im/app/models"
	"im/app/models/form/user"
	validator2 "im/app/models/validator"
	"im/app/services"
	"im/app/util/response"
)

type Auth struct {}

// 登录
func (a *Auth) Login(c *gin.Context) {
	inputs := user.UserLogin{}
	err := c.ShouldBind(&inputs)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		response.ReturnJsonOk(c, validator2.OutErrors(errs))
		return
	}
	us := services.UserService{}
	res, err := us.Login(inputs.Name, inputs.Password)

	if err != nil{
		response.ReturnJsonOk(c, err.Error())
		return
	}else {
		response.ReturnJsonOk(c, "登录成功", res)
		return
	}

	response.ReturnJsonOk(c, "登录失败")
}

// 注册
func (a *Auth) Register(c *gin.Context) {
	inputs := user.UserRegister{}
	err := c.ShouldBind(&inputs)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		//设置转换器
		response.ReturnJsonOk(c, validator2.OutErrors(errs))
		return
	}
	us := services.UserService{}
	err = us.Register(&inputs)
	if err != nil {
		response.ReturnJsonOk(c, err.Error())
		return
	}

	response.ReturnJsonOk(c, "注册成功", nil)
}

// 用户信息
func (a *Auth) GetUserInfo(c *gin.Context) {
	inputs := user.UserGetUserInfo{}
	err := c.ShouldBind(&inputs)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		//设置转换器
		response.ReturnJsonOk(c, validator2.OutErrors(errs))
		return
	}
	if inputs.UserId >0 {
		admin := models.User{}
		conf.Mdb.Select("id,name,sex").Where("id=?",inputs.UserId).Take(&admin)

		response.ReturnJsonOk(c, "成功", admin)
		return
	}else {
		adminObj,_ := c.Get(models.ContextKeyUserObj)
		admin := adminObj.(*models.User)

		response.ReturnJsonOk(c, "成功", admin)
	}
}